﻿/** 
 * Description: 订单管理
 * Date:2011-7-17
 * Author:Along	
*/
package com.community.shopping.service.logic;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.community.shopping.dao.OrderDao;
import com.community.shopping.dao.OrderItemDao;
import com.community.shopping.domain.Goods;
import com.community.shopping.domain.Order;
import com.community.shopping.domain.OrderItem;
import com.community.shopping.domain.User;
import com.community.shopping.util.MailTest;

public class OrderManager {
	
	private OrderDao orderDao;
    
	/**
	 * @param orderDao the orderDao to set
	 */
	public void setOrderDao(OrderDao orderDao) {
		this.orderDao = orderDao;
	}
	private OrderItemDao itemDao;
	/**
	 * @param itemDao the itemDao to set
	 */
	public void setItemDao(OrderItemDao itemDao) {
		this.itemDao = itemDao;
	}
	private GoodsManager goodsManager;
	/**
	 * @param goodsManager the goodsManager to set
	 */
	public void setGoodsManager(GoodsManager goodsManager) {
		this.goodsManager = goodsManager;
	}
	private UserScoreManager userScoreManager;
	
	/**
	 * @param userScoreManager the userScoreManager to set
	 */
	public void setUserScoreManager(UserScoreManager userScoreManager) {
		this.userScoreManager = userScoreManager;
	}
	private SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public void saveOrder(Order order)
	{
		orderDao.save(order);		
	}
	
	/**
	 * 修改订单状态 0:取消  5:下达 10:拣货中 15:配送中 20:已完成
	 * @param order
	 * @param status
	 */	
	public void saveOrder(Order order,Integer status)
	{
		if(status==0)
		{
		  cancelOrder(order);	
		}else if(status==20)
		{
		  //scoreOrder(order);	update 2012-7-20 评论之后再获得积分
		}
		order.setStatus(status);
		orderDao.save(order);		
	}
	
	/**
	 * 取消订单,恢复库存和用户积分(用户积分先不退还)
	 * @param order
	 */
	private void cancelOrder(Order order)
	{
		List<OrderItem> orderItem=itemDao.getOrderItem(" orderId = '"+ order.getId()+"'");
		for(OrderItem item:orderItem)
		{
			Integer goodsId=item.getGoodsId();
			Integer num=item.getNum();
			Goods goods=goodsManager.getGoodsById(goodsId);
			goods.setGoodsNum(goods.getGoodsNum()+num);
			goodsManager.save(goods);
		}		
	}
	
	/**
	 * 评论后，结算所得积分
	 * @param order
	 */
	public void saveOrderScore(Order order)
	{
		order.setIfComment(1);
		orderDao.save(order);
		userScoreManager.addScore(order);
		/*List<OrderItem> orderItem=itemDao.getOrderItem(" orderId = '"+ order.getId()+"'");
		for(OrderItem item:orderItem)
		{
			Integer goodsId=item.getGoodsId();
			Integer num=item.getNum();
			Goods goods=goodsManager.getGoodsById(goodsId);
			goods.setSaleNum((goods.getSaleNum()==null?0:goods.getSaleNum())+num);
			goodsManager.save(goods);
		}		*/
	}
	
	
	/**
	 * 确认订单界面确认送货时根据当前user和cookie中记录的购物车信息生成订单
	 * @param user 当前user
	 * @param cookieGoods cookie中记录的购物车信息
	 * @return 如果不缺货，返回订单信息，如果缺货，返回缺货提示信息
	 */
	public String saveOrderByCookie(User user,String cookieGoods,String memo)
	{
		String error=checkOrder(cookieGoods,user);
		if(error==null)//如果没有异常信息,保存订单
		{
			Order order=new Order();
			order.setOrderUser(user);
			order.setOrderNo(createOrderNum());
			order.setReceiveUser(user.getRealName());
			order.setReceiveContact(user.getUserName());
			order.setReceiveAddress(user.getAddress());
			order.setStatus(5);
			order.setCreateDate(format.format(new Date()));
			order.setIfComment(0);
			order.setDescription(memo);
			orderDao.save(order);
			String [] goodslist=cookieGoods.split(",");	
			float totalprice=0;
			float costtotalprice=0;
			int totalScore=0;
			for(int i=0;i<goodslist.length;i++)
			{
				String goodsId=goodslist[i].split("_")[0];
				Integer num=Integer.parseInt(goodslist[i].split("_")[1]);
				Integer kind=Integer.parseInt(goodslist[i].split("_")[2]);
				Goods goods=goodsManager.getGoodsById(Integer.parseInt(goodsId));
				OrderItem item= new OrderItem();
				item.setOrderId(order.getId());
				item.setOrderNo(order.getOrderNo());			
				item.setKind(kind);			
				item.setPrice(goods.getPrice());
				//item.setScore(goods.getScorePrice());
				item.setCostPrice(goods.getCostPrice());
				item.setCostTotalPrice(num*item.getCostPrice());
				item.setNum(num);
				item.setTotalPrice(num*item.getPrice());
				item.setTotalScore(num*item.getScore());
				item.setGoodsName(goods.getGoodsName());
				item.setGoodsCode(goods.getGoodsNO());
				item.setGoodsId(goods.getId());
				itemDao.save(item);
				//扣除商品库存
				goods.setGoodsNum(goods.getGoodsNum()-num);
				goods.setSaleNum((goods.getSaleNum()==null?0:goods.getSaleNum())+num);
				goodsManager.save(goods);
				if(kind==0)
				{
				totalprice=totalprice+item.getTotalPrice();
				}
				else if(kind==1)//积分兑换商品计算订单总共需要的积分
				{
				totalScore=totalScore+item.getTotalScore();
				}
				costtotalprice=costtotalprice+item.getCostTotalPrice();
			}
			order.setTotalPrice(totalprice);
			order.setScore(totalScore);
			order.setCostTotalPrice(costtotalprice);
			if(totalprice<20)//如果订单总金额小于20块，收一元运费
			{
				order.setYfPrice(2);
			}
			orderDao.save(order);
			//扣除用户积分
			if(order.getScore()>0)
			userScoreManager.delScore(order);
			
			//发送邮件通知
			String title=order.getOrderNo().substring(8,10)+","+order.getReceiveUser()+","+"￥"+order.getTotalPrice()+","
			+order.getReceiveAddress()+","+order.getDescription();
			Thread t=new MailTest(title);
			t.start();
			return "true";
			
		}else //如果有订单中商品数量超过库存量，返回异常信息
		{
			return error;
			
		}
	}
	
	public List queryOrder(String hql)
	{
		return orderDao.getOrder(hql);	
	}
	
	public String sumOrder(String hql)
	{
		
		return orderDao.sumOrder(hql);
	}
	
	public Order queryOrderById(String id)
	{
		Order order=orderDao.getOrderById(id);	
		List items=itemDao.getOrderItem(" orderId="+id);
		order.setOrderList(items);
		return order;
	}
	
	private  String createOrderNum()
	{   
		SimpleDateFormat format=new SimpleDateFormat("yyyyMMdd");
		String dateNum=format.format(new Date());
		//String nextNum=dateNum+"-"+formatNum(1,3);
		java.util.Random ran=new java.util.Random();
		String nextNum=dateNum+"11"+String.valueOf(ran.nextInt(10))+String.valueOf(ran.nextInt(10));
		String maxNum=orderDao.getMaxNum(dateNum);
		if(!maxNum.equals(""))
		{
			int currentNum=Integer.parseInt(maxNum.substring(8,10));
			nextNum=dateNum+formatNum(currentNum+1,2)+String.valueOf(ran.nextInt(10))+String.valueOf(ran.nextInt(10));
		}
		return nextNum;
	}
	
	private String formatNum(int num,int size)
	{
		String result=String.valueOf(num);
		while(result.length()<size)
		{			
			result="0"+result;
		}
	  return result;	
	}
	/**
	 * 检查订单中各笔商品数量是否大于库存
	 * @param cookieGoods
	 * @return
	 */
	private String checkOrder(String cookieGoods,User user){
		Integer totalScore=0;
		String [] goodslist=cookieGoods.split(",");	
		StringBuilder sb=new StringBuilder("[");
		boolean flag=true;
		for(int i=0;i<goodslist.length;i++)
		{
			String goodsId=goodslist[i].split("_")[0];
			Integer num=Integer.parseInt(goodslist[i].split("_")[1]);
			Integer kind=Integer.parseInt(goodslist[i].split("_")[2]);
			Goods goods=goodsManager.getGoodsById(Integer.parseInt(goodsId));
			if(goods.getGoodsNum()<num)//库存量小于订单中商品数量
			{
				flag=false;
				if(sb.length()>1)
				{
					sb.append(",");
				}
				sb.append("{\"index\":\""+i+"\",\"number\":\""+goods.getGoodsNum()+"\"}");
			}
			if(kind==1)//积分交换
			{
				//totalScore=totalScore+goods.getScorePrice()*num; 
			}
		}
		if(user.getScore()<totalScore)
		{
			if(sb.length()>1)
			{
				sb.append(",");
			}
			sb.append("{\"index\":\""+-1+"\",\"number\":\""+user.getScore()+"\"}");	
			flag=false;
		}
		sb.append("]");
		if(flag)//订单中商品数量没有异常情况，均在库存量之内
		{
		 return null;
		}
		else 
		{
		 return sb.toString();	
		}
	}
	
	public List queryOrder(String hql,Page page)
	{
		return orderDao.getOrder(hql,page);	
	}
	
	//返利数据求和
	public String queryRebackSum(String hql)
	{
		return orderDao.sumRebackOrder(hql);
				
	}

}
